package ru.btabank.dom.xpath.expression;

import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Locale;

import org.w3c.dom.Node;

import ru.btabank.dom.util.DOMUtil;
import ru.btabank.dom.xpath.XPathException;

public class StringFunction extends FunctionCall {

    public StringFunction() {
        super();
    }

    public Object evaluate(NodeSet context) throws XPathException {
        ArrayList values = super.evaluateValues(context);
        Object value;

        if (values.size() != 1)
            throw new XPathException("string() function requires one argument.");
        else
            value = values.get(0);

        if (value instanceof NodeSet) {
            NodeSet nodeSet = (NodeSet)value;
            if (nodeSet.getLength() == 0)
                return "";
            Node node = nodeSet.item(0);
            switch (node.getNodeType()) {
            case Node.DOCUMENT_NODE:
            case Node.ELEMENT_NODE:
                return DOMUtil.getTextNodesValue(node);
            case Node.ATTRIBUTE_NODE:
            case Node.TEXT_NODE:
            case Node.COMMENT_NODE:
                return node.getNodeValue();
            default:
                return "";
            }
        } else if (value instanceof Double) {
            DecimalFormat format = (DecimalFormat)NumberFormat.getInstance(Locale.ENGLISH);
            format.setGroupingUsed(false);
            format.setMaximumFractionDigits(32);
            return format.format(value);
        } else if (value instanceof Boolean)
            return value.toString();

        return value.toString();
    }
}
